import { RuntimeModelError } from '@ibiz-template/core';
import {
  getEditorProvider,
  IEditorContainerController,
  IEditorController,
  IEditorProvider,
} from '@ibiz-template/runtime';
import { IPanelField } from '@ibiz/model-core';
import { PanelItemController } from '../../control';
import { PanelFieldState } from './panel-field.state';

/**
 * 面板按钮控制器
 *
 * @export
 * @class PanelFieldController
 * @extends {PanelItemController<IPanelField>}
 */
export class PanelFieldController
  extends PanelItemController<IPanelField>
  implements IEditorContainerController
{
  declare state: PanelFieldState;

  unitName: string | undefined = undefined;

  /**
   * 值格式化
   * @author lxm
   * @date 2023-05-24 05:46:56
   * @readonly
   * @type {(string | undefined)}
   */
  get valueFormat(): string | undefined {
    return this.model.valueFormat;
  }

  get context(): IContext {
    return this.panel.context;
  }

  get params(): IParams {
    return this.panel.params;
  }

  /**
   * 父容器数据对象数据
   * @author lxm
   * @date 2023-07-15 01:33:58
   * @readonly
   * @type {IData}
   */
  get data(): IData {
    return this.dataParent.data;
  }

  /**
   * 面板属性成员的值
   * @author lxm
   * @date 2023-07-14 02:30:58
   * @readonly
   */
  get value(): string | number {
    const { viewFieldName } = this.model;
    if (!viewFieldName) {
      throw new RuntimeModelError(this.model, '没有绑定数据项');
    }
    return this.data[viewFieldName.toLowerCase()];
  }

  /**
   * 编辑器控制器
   *
   * @author lxm
   * @date 2022-08-24 20:08:42
   * @type {IEditorController}
   */
  editor?: IEditorController;

  /**
   * 编辑器适配器
   *
   * @author lxm
   * @date 2022-08-24 20:08:42
   */
  editorProvider?: IEditorProvider;

  protected createState(): PanelFieldState {
    return new PanelFieldState(this.parent?.state);
  }

  /**
   * 初始化
   *
   * @author lxm
   * @date 2022-08-24 20:08:42
   * @protected
   * @returns {*}  {Promise<void>}
   */
  protected async onInit(): Promise<void> {
    await super.onInit();
    // 空输入默认值
    this.state.required = !this.model.allowEmpty;
    // 初始化编辑器控制器,除了隐藏都会需要适配器
    if (this.model.editor && this.model.editor.editorType !== 'HIDDEN') {
      this.editorProvider = await getEditorProvider(this.model.editor);
      if (this.editorProvider) {
        this.editor = await this.editorProvider.createController(
          this.model.editor,
          this,
        );
      }
    }
  }
}
